﻿using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace XXX.api.Filter
{
    public class RequestBodyCachingMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestBodyCachingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            // 只处理 JSON 请求
            if (request.ContentLength > 0 &&
                request.ContentType?.Contains("application/json") == true)
            {
                request.EnableBuffering();
                using var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true);
                string body = await reader.ReadToEndAsync();
                request.Body.Position = 0; // 重置流位置

                context.Items["CachedRequestBody"] = body;
            }

            await _next(context);
        }
    }
}
